import React, { Component, Suspense } from 'react';
import { connect } from 'dva';
import { Form, Input, Icon, Button, message } from 'antd';

let id = 0;
@connect(({ editQa }) => ({
  editQa,
}))
class QuestionNew extends Component {
  constructor(props) {
    super(props);
    this.state = {
      questions: props.editQa.list,
      question: '',
      qaId: props.qaId,
      search: {
        limit: 6,
        page: 1,
        text: '',
      },
      keyArr: [],
    };
  }

  componentDidMount() {
    // this.getQuestion();
  }

  remove = (k, index) => {
    const { form } = this.props;
    let { questions } = this.state;
    const keys = form.getFieldValue('keys');
    if (keys.length === 1) {
      return;
    }
    questions = questions.filter(key => key !== questions[index]);
    this.setState(
      {
        questions,
      },
      () => {
        form.setFieldsValue({
          keys: keys.filter(key => key !== k),
        });
      }
    );
  };

  up = (k,index) => {
    const { form } = this.props;
    let { questions } = this.state;
    let keys = form.getFieldValue('keys');
    if (keys.length === 1) {
      return;
    }
    keys.unshift(keys.splice(k, 1)[0]);
    questions.unshift(questions.splice(index, 1)[0]);
    this.setState({
      questions
    },()=>{
      form.setFieldsValue({
        keys,
      });
    })
  };

  add = e => {
    const { form } = this.props;
    let { questions } = this.state;
    e.preventDefault();
    var regu = '^[ ]+$';
    var re = new RegExp(regu);
    if (!e.target.value) {
      message.error('问题不可为空');
      return false;
    }

    if (re.test(e.target.value)) {
      message.error('问题不可为空');
      return false;
    } else {
      const val = e.target.value;
      if (questions.indexOf(val) > 0) {
        return message.error('相似问/标准问【' + val + '】已存在');
      }

      questions = [...questions, val];
      this.setState(
        {
          questions,
          question: '',
        },
        () => {
          let keys = form.getFieldValue('keys');
          id = id + 1;
          keys.push(id);
          form.setFieldsValue({
            keys,
          });
        }
      );
    }
  };

  changeQuestion = e => {
    this.setState({
      question: e.target.value,
    });
  };

  handleSubmit = e => {
    e.preventDefault();
    this.props.form.validateFields((err, values) => {
      if (!err) {
        const { keys, names } = values;


          'Merged values:',
          keys.map(key => names[key])
        );
      }
    });
  };

  getQuestion = () => {
    const { dispatch } = this.props;
    let { search, qaId, questions, keyArr } = this.state;
    this.reqRef = requestAnimationFrame(() => {
      dispatch({
        type: 'editQa/getQuestionsByQaId',
        payload: {
          id: qaId,
          limit: search.limit,
          page: search.page,
          search: search.text,
        },
        callback: res => {
          for (let i = 0; i < res.list.length; i++) {
            questions.push(res.list[i].question);
            keyArr.push(i);
          }
          id = res.list.length;
          this.setState({
            questions,
            keyArr,
            total:res.total
          });
        },
      });
    });
  };

  getComm=()=>{
    const { dispatch } = this.props;
    let { search, qaId, questions, keyArr } = this.state;
    this.reqRef = requestAnimationFrame(() => {
      dispatch({
        type: 'editQa/getStandardQuestionByQaId',
        payload: {id:qaId},
        callback: (res) => {
          this.setState({
            standardQus: res.question
          })
        }
      })
    })
  };

  seeMore=()=>{
    this.props.seeMore(true)
  };

  render() {
    const { getFieldDecorator, getFieldValue } = this.props.form;
    let { questions, question, keyArr,total } = this.state;
    const formItemLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 2 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 22 },
      },
    };
    const formItemLayoutWithOutLabel = {
      wrapperCol: {
        xs: { span: 24, offset: 0 },
        sm: { span: 22, offset: 2 },
      },
    };

    getFieldDecorator('keys', { initialValue: keyArr });
    const keys = getFieldValue('keys');
    const formItems = keys.map((k, index) => (
      <Form.Item
        {...(index === 0 ? formItemLayout : formItemLayoutWithOutLabel)}
        label={index === 0 ? '标准问' : ''}
        required={false}
        key={index}
      >
        {getFieldDecorator(`names[${k}]`, {
          validateTrigger: ['onChange', 'onBlur'],
          initialValue: questions[index],
          rules: [
            {
              required: true,
              whitespace: true,
              message: '相似问/标准问不能为空，请完善后再保存',
            },
          ],
        })(
          <Input
            placeholder="请输入相似问"
            style={{ width: '90%', marginRight: 8 }}
            onPressEnter={this.add}
          />
        )}
        {questions.length > 1 ? (
          <Icon
            className="dynamic-delete-button"
            type="close-circle"
            onClick={() => this.remove(k, index)}
          />
        ) : null}
        {questions.length > 1 ? (
          <Icon
            className="dynamic-delete-button"
            style={{ marginLeft: 10 }}
            type="arrow-up"
            onClick={() => this.up(k,index)}
          />
        ) : null}
      </Form.Item>
    ));
    return (
      <Form onSubmit={this.handleSubmit}>
        <Form.Item {...formItemLayoutWithOutLabel} label={''} required={false}>
          <Input
            placeholder="请输入相似问，点击/回车继续添加"
            style={{ width: '90%', marginRight: 8 }}
            value={question}
            onChange={e => this.changeQuestion(e)}
            onPressEnter={e => this.add(e)}
          />
          <Icon className="dynamic-delete-button" type="plus" onClick={() => this.remove()} />
        </Form.Item>
        {formItems}
        <Form.Item {...formItemLayoutWithOutLabel}>
          <div style={{textAlign: 'center'}}>
            {total?<Button htmlType='button' style={{ margin: '0 auto' }} onClick={()=>this.seeMore()}>查看全部相似问</Button>:''}
          </div>
        </Form.Item>
      </Form>

    );
  }
}

export default connect(({ user }) => ({
  currentUser: user.currentUser,
}))(Form.create()(QuestionNew));
